/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src.services.saving;

import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import src.domain.saving.Savprod;

/**
 *
 * @author Lalugina
 */
public class SavprodConverter implements Converter{
    
    public static List<Savprod> products;

    static {
        products = new SavprodModel().findAll(null);        
    }

    @Override
    public Object getAsObject(FacesContext fc, UIComponent uic, String submittedValue) {
        if (submittedValue.trim().equals("")) {
            return null;
        } else {
            try {
                int number = Integer.parseInt(submittedValue);
                for (Savprod p : products) {
                    if (p.getSavproductId() == number) {
                        return p;
                    }
                }

            } catch(NumberFormatException exception) {
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid product"));
            }
        }
        
        return null;
    }

    @Override
    public String getAsString(FacesContext fc, UIComponent uic, Object value) {
        if (value == null || value.equals("")) {
            return "";
        } else {
            return String.valueOf(((Savprod) value).getSavproductId());
        }
    }
    
    
}
